package com.lad.filter;

import com.alibaba.fastjson.JSON;
import com.lad.api.CommonResult;
import com.lad.utils.UtilWeb;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.context.annotation.Configuration;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

/**
 * 处理外部系统绕过网关直接访问访问的安全问题
 */
@Configuration
@WebFilter(urlPatterns = "/*", filterName = "requestFilter")
@Slf4j
public class RequestSecurityFilter implements Filter {

    @Autowired
    private DiscoveryClient discoveryClient;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        String ipAddr = UtilWeb.getIpAddr(httpServletRequest);
        List<String> services = discoveryClient.getServices();
        boolean flag = false;
        bgm:for (String s : services) {
            List<ServiceInstance> instances = discoveryClient.getInstances(s);
            for (ServiceInstance si : instances) {
                String host = si.getHost();
                if (ipAddr.equals(host)) {
                    flag = true;
                    break bgm;
                }
            }
        }
        if (flag) {
            filterChain.doFilter(servletRequest, servletResponse);
        } else {
            CommonResult<String> commonResult = CommonResult.forbiddenSecurity("请通过网关访问服务");
            String msg = JSON.toJSONString(commonResult);
            ((HttpServletResponse) servletResponse).setStatus(commonResult.getCode());
            servletResponse.setCharacterEncoding("UTF-8");
            servletResponse.setContentType("application/json; charset=utf-8");
            PrintWriter out = null;
            try {
                out = servletResponse.getWriter();
                out.append(msg);
                out.flush();
            }catch (IOException e){
                log.error("安全过滤---异常提示：输出错误提示信息异常！" + e);
            } finally {
                IOUtils.closeQuietly(out);
            }
        }
    }

    @Override
    public void destroy() {

    }
}
